package application;

import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.LinkedList;
import java.util.List;

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;


public class Puzzle {
	
	public static final int NUM_OF_ROW = 3;
	public static final int NUM_OF_COL = 3;
	
	private static final String CONF_FILE = "config/puzzles.json";
	
	private static final String HELPWORD_KEY = "helpword";
	private static final String KEYWORD_KEY = "keyword";
	
	
	private Piece[][] pieces;
	
	
	private Puzzle(Piece[][] pieces) {
		this.pieces = pieces;
	}
	
	
	public Piece getPiece(int rowIdx, int colIdx) {
		return pieces[rowIdx][colIdx];
	}
	
	public void setGuessed(String keyword, boolean isGuessed) {
		for(int i = 0; i < NUM_OF_ROW; i++)
			for(int j = 0; j < NUM_OF_COL; j++) {
				Piece piece = pieces[i][j];
				if(piece.getKeyWord().equals(keyword))
					piece.setGuessed(isGuessed);
			}
	}
	
	public boolean isWon() {
		for(int i = 0; i < NUM_OF_ROW; i++)
			for(int j = 0; j < NUM_OF_COL; j++)
				if(!pieces[i][j].isGuessed())
					return false;
		return true;
	}

	
	public static List<Puzzle> readPuzzles() {
		List<Puzzle> puzzles = new LinkedList<Puzzle>();
		
		JSONParser parser = new JSONParser();
		
		try {
			JSONArray puzzleArray = (JSONArray) parser.parse(new FileReader(CONF_FILE));
			
			for(Object pieceArray : puzzleArray) {
				puzzles.add(readPuzzle((JSONArray) pieceArray));
			}
			
		} catch (IOException | ParseException e) 
		{ e.printStackTrace(); }
		
		return puzzles;
	}
	
	private static Puzzle readPuzzle(JSONArray pieceArray) {
		Piece[][] pieces = new Piece[NUM_OF_ROW][NUM_OF_COL];
		
		int pieceIdx = 0;
		for(Object pieceObject : pieceArray) {
			int colIdx = pieceIdx % NUM_OF_COL;
			int rowIdx = (pieceIdx - colIdx) / NUM_OF_COL;
			
			JSONObject pieceJSONObject = (JSONObject) pieceObject;
			String helpWord = (String) pieceJSONObject.get(HELPWORD_KEY);
			String keyWord = (String) pieceJSONObject.get(KEYWORD_KEY);
			
			pieces[rowIdx][colIdx] = new Piece(rowIdx, colIdx, helpWord, keyWord);
			
			pieceIdx++;
		}
		
		return new Puzzle(pieces);
	}
	
}
